(function(){
    var el = document.getElementById('app');
    $.ajax({
        type: 'GET',
        url: window.location.origin + '/news/list',
        datatype: 'json',
        success: function (resp) {
            if (resp.status === '0') {
                appCreate(el, resp.result.list);
            }
        }, 
        error: function () {
            alert('网络有误！');
        }
    })
}());

function appCreate (root , data) {
    if (!data || data.length < 1) {
        return;
    }
    for (var index = 0; index < data.length; index++) {
        let _data = data[index];
        var newsItemEl = elCreator('div', 'news-item', '', {
            onclick: function () {
                if (window.sessionStorage) {
                    sessionStorage.setItem('NEW_DETAIL', JSON.stringify(_data));
                }
                window.location.href = 'detail.html';
            }
        });
        root.appendChild(newsItem(newsItemEl, _data));
    }
}

function newsItem(root , data) {
    var left = elCreator('div', 'left');
    var title = elCreator('h3', 'title', data.title);
    var tip = elCreator('div', 'tip');
    if (data.src) {
        tip.appendChild(elCreator('span', 'source', data.src));
    }
    if (data.time) {
        tip.appendChild(elCreator('span', 'time', data.time));
    }
    left.appendChild(title);
    left.appendChild(tip);
    root.appendChild(left)
    if (data.pic) {
        var right = elCreator('div', 'right');
        var pic = elCreator('div', 'pic');
        pic.appendChild(elCreator('img', '', '', {src: data.pic}));
        right.appendChild(pic);
        root.appendChild(right);
    }
    return root;
}

function elCreator(tag, _class, text, props) {
    var el = document.createElement(tag);
    el.classList = _class;
    if (props) {
        for (var key in props) {
            el[key] = props[key]
        }
    }
    if (text) {
        el.innerHTML = text;
    }
    return el;
}